/*
  Losu Copyright Notice
  --------------------
    Losu is an open source programming language project under the MIT license
  that can be used for both academic and commercial purposes. There are no
  fees, no royalties, and no GNU-like restrictions. Losu qualifies
  as open source software. However, Losu is not public property, and founder
  'chen-chaochen' retains its copyright.

    Losu has been registered with the National Copyright Administration of the
  People's Republic of China, and adopts the MIT license as the copyright
  licensing contract under which the right holder conditionally licenses its
  reproduction, distribution, and modification rights to an unspecified public.

    If you use Losu, please follow the public MIT agreement or choose to enter
  into a dedicated license agreement with us.

  The MIT LICENSE is as follows
  --------------------
  Copyright  2020  chen-chaochen

    Permission is hereby granted, free of charge, to any person obtaining a
  copy of this software and associated documentation files (the “Software”), to
  deal in the Software without restriction, including without limitation the
  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  sell copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
*/

#ifndef FILE_SRC_SYNTAX_PARSER_C
#define FILE_SRC_SYNTAX_PARSER_C

#include "parser.h"
#include "losu_mem.h"
#include "losu_object.h"

#include <stdio.h>

/**
 * @brief parse the source code
 * @param vm losu vm handle
 * @param io in io handle
 * @return  the scode object
 */
losu_object_scode_t losu_syntax_parse(losu_vm_t vm, losu_syntax_io_t io) {
  losu_syntax_lex lex = {0};
  lex.idt = (losu_syntax_lex_idt){
      .nowidt = 0,
      .read = 0,
      .size = 4,
      .tmp = 0,
  };
  losu_syntax_func func = {0};
  losu_ctype_bool islast = 0;
  __losu_syntaxpar_setin(vm, &lex, io);

  return func.fcode;
}

static void __losu_syntaxpar_setin(losu_vm_t vm,
                                   losu_syntax_lex_t lex,
                                   losu_syntax_io_t io) {
  lex->vm = vm;
  lex->tkahead.token = TOKEN_EOZ;
  lex->io = io;
  lex->fs = NULL;
  lex->lastline = lex->linenumber = 1;
}

/**
 * control segment
 * ----------------
 * control the syntax parse
 */
#if 1
static void __losu_syntaxpar_token2str(int16_t tk, char* buf) {
  if (tk < 255) {
    buf[0] = (char)((unsigned char)tk);
    buf[1] = '\0';
  } else
    snprintf(buf, 16, "%s", losu_syntax_keyword[tk - TOKEN_AND].str);
}

static void __losu_syntaxpar_error(losu_syntax_lex_t lex, int16_t tk) {
  char t[16] = {0};
  __losu_syntaxpar_token2str(tk, t);
  losu_syntax_error(lex, "excpected '%s'", t);
  return;
}

static void __losu_syntaxpar_newfunc(losu_syntax_lex_t lex,
                                     losu_syntax_func_t func) {
  losu_object_scode_t f = (losu_object_scode_t)losu_objsocde_new(lex->vm);
  func->prev = lex->fs;
  func->lexer = lex;
  func->vm = lex->vm;
  func->stacklevel = 0;
  func->naloc = 0;
  func->nclosure = 0;
  func->breaklist = NULL;
  func->fcode = f;
  func->pc = 0;
  func->lasttarget = 0;
  func->lastline = 0;
  func->jump = NO_JUMP;

  lex->fs = func;

  f->code = NULL;
  f->maxstacksize = 0;
  f->narg = 0;
  f->isVarg = 0;
  f->marked = 0;
}

static void __losu_syntaxpar_delfunc(losu_syntax_lex_t lex) {
  losu_vm_t vm = lex->vm;
  losu_syntax_func_t func = lex->fs;
  losu_object_scode_t f = func->fcode;
  losu_syntax_codegenarg0(func, INS_END);
  losu_syntax_binder_getL(func);
  __losu_syntaxpar_removelcvar(lex, func->naloc);
  losu_mem_reallocvector(vm, f->localvar, f->nlocalvar, losu_objscode_locvar);
  losu_mem_reallocvector(vm, f->code, func->pc, losu_ctype_vmins_t);
  losu_mem_reallocvector(vm, f->lcstr, f->nlcstr, losu_object_string_t);
  losu_mem_reallocvector(vm, f->lcnum, f->nlcnum, losu_ctype_number);
  losu_mem_reallocvector(vm, f->lcscode, f->nlcscode, losu_object_scode_t);
  losu_mem_reallocvector(vm, f->lineinfo, f->nlineinfo + 1, int32_t);
  f->lineinfo[f->nlineinfo++] = INT32_MAX;

#define sizeObjScode(f)                                                 \
  ((sizeof(losu_object_scode) + f->nlcnum * sizeof(losu_ctype_number) + \
    f->nlcstr * sizeof(losu_object_string_t) +                          \
    f->nlcscode * sizeof(losu_object_scode_t) +                         \
    f->ncode * sizeof(losu_ctype_vmins_t) +                             \
    f->nlocalvar * sizeof(losu_objscode_locvar) +                       \
    f->nlineinfo * sizeof(int32_t)))

  f->ncode = func->pc;
  vm->nblocks += sizeObjScode(f);
#undef sizeObjScode
  lex->fs = func->prev;
}

static void __losu_syntaxpar_check(losu_syntax_lex_t lex, int16_t tk) {
  if (lex->tk.token != tk)
    __losu_syntaxpar_error(lex, tk);
  __losu_syntaxpar_next(lex);
}

static losu_ctype_bool __losu_syntaxpar_checkblock(int16_t tk) {
  switch (tk) {
    case TOKEN_ELSE:
    case TOKEN_ELSEIF:
    case TOKEN_PASS:
    case TOKEN_EOZ:
      return 1;
    default:
      return 0;
  }
  return 0;
}

static void __losu_syntaxpar_checkcondtion(losu_syntax_lex_t lex,
                                           losu_ctype_bool c,
                                           const char* errmsg) {
  if (!c)
    losu_syntax_error(lex, errmsg);
}

static void __losu_syntaxpar_checkmatch(losu_syntax_lex_t lex,
                                        int16_t l,
                                        int16_t r,
                                        int32_t line) {
  if (lex->tk.token != r) {
    char tl[16], tr[16];
    __losu_syntaxpar_token2str(l, tl);
    __losu_syntaxpar_token2str(r, tr);
    losu_syntax_error(lex, " '%s'\t(line %d) \texpected '%s' ", tl, line, tr);
  }
  __losu_syntaxpar_next(lex);
}

static losu_object_string_t __losu_syntaxpar_checkname(losu_syntax_lex_t lex) {
  losu_object_string_t ts;
  __losu_syntaxpar_checkcondtion(lex, lex->tk.token == TOKEN_NAME,
                                 " expected name ");
  ts = lex->tk.info->s;
  __losu_syntaxpar_next(lex);
  return ts;
}

static void __losu_syntaxpar_checklimit(losu_syntax_lex_t lex,
                                        int32_t v,
                                        int32_t l,
                                        const char* errmsg) {
  if (v <= l)
    return;
  losu_syntax_error(lex, "Too mant %s (limit %d)", errmsg);
}

static void __losu_syntaxpar_newlcvar(losu_syntax_lex_t lex,
                                      losu_object_string_t name,
                                      int16_t i) {
  losu_syntax_func_t func = lex->fs;
  losu_object_scode_t f = func->fcode;
  __losu_syntaxpar_checklimit(lex, func->naloc + i + 1, _losu_vmlim_maxlocvar,
                              "local variables");
  losu_mem_growvector(lex->vm, f->localvar, f->nlocalvar, 1,
                      losu_objscode_locvar, _losu_vmins_maxA, "[local var]");
  f->localvar[f->nlocalvar].name = name;
  func->aloc[func->naloc + i] = f->nlocalvar++;
}

static void __losu_syntaxpar_removelcvar(losu_syntax_lex_t lex, int16_t i) {
  losu_syntax_func_t func = lex->fs;
  while (i--)
    func->fcode->localvar[func->aloc[--(func->naloc)]].endpc = func->pc;
}

static void __losu_syntaxpar_next(losu_syntax_lex_t lex) {
  lex->lastline = lex->linenumber;
  if (lex->tkahead.token != TOKEN_EOZ) {
    lex->tk = lex->tkahead;
    lex->tkahead.token = TOKEN_EOZ;
  } else
    lex->tk.token =
        losu_syntax_lex_next(lex, (losu_syntax_tkvalue_t)(&(lex->tk.info)));
}

#endif

/**
 * stat = {if | while | until | for | def | var | name | return | break | block
 *  */
#if 1
static losu_ctype_bool __losu_syntaxpar_stat(losu_syntax_lex_t lex) {
  int32_t line = lex->linenumber;
  switch (lex->tk.token) {
    case TOKEN_IF: {
      lex->deepth++;
      __losu_syntaxpar_statif(lex, line);
      lex->deepth--;
      break;
    }
    case TOKEN_WHILE: {
      lex->deepth++;
      __losu_syntaxpar_statwhile(lex, line);
      lex->deepth--;
      break;
    }
    case TOKEN_UNTIL: {
      lex->deepth++;
      __losu_syntaxpar_statuntil(lex, line);
      lex->deepth--;
      break;
    }
    case TOKEN_FOR: {
      lex->deepth++;
      __losu_syntaxpar_statfor(lex, line);
      lex->deepth--;
      break;
    }
    case TOKEN_DEF: {
      lex->deepth++;
      __losu_syntaxpar_statfunc(lex, line);
      lex->deepth--;
      break;
    }
    case TOKEN_VAR: {
      __losu_syntaxpar_statvar(lex);
      break;
    }
    case TOKEN_NAME: {
      __losu_syntaxpar_statname(lex);
      break;
    }
    case TOKEN_RETURN: {
      __losu_syntaxpar_statreturn(lex);
      return 1;
    }
    case TOKEN_BREAK: {
      __losu_syntaxpar_statbreak(lex);
      return 1;
    }
    case TOKEN_CONTINUE: {
      __losu_syntaxpar_statcontinue(lex);
      return 1;
    }
    case TOKEN_YIELD: {
      __losu_syntaxpar_statyield(lex);
      break;
    }
    default: {
      losu_syntax_error(lex, "invalid expression ");
      break;
    }
  }
  return 0;
}

static void __losu_syntaxpar_statif(losu_syntax_lex_t lex, int32_t line) {
#define condition(lex, v)                      \
  {                                            \
    __losu_syntaxpar_subexp((lex), (v), -1);   \
    losu_syntax_binder_goT((lex)->fs, (v), 0); \
  }

#define then(lex, v)                    \
  {                                     \
    __losu_syntaxpar_next((lex));       \
    condition((lex), (v));              \
    __losu_syntaxpar_check((lex), ':'); \
    __losu_syntaxpar_statblock((lex));  \
  }

  losu_syntax_func_t func = lex->fs;
  losu_syntax_exp v;
  int32_t el = NO_JUMP;
  then(lex, &v);
  while (lex->tk.token == TOKEN_PASS) {
    __losu_syntaxpar_next(lex);
    if (lex->tk.token == TOKEN_ELSEIF) {
      losu_syntax_binder_concat(func, &el, losu_syntax_binder_jump(func));
      losu_syntax_binder_palist(func, v.value._bool.f,
                                losu_syntax_binder_getL(func));
      then(lex, &v);
    } else if (lex->tk.token == TOKEN_ELSE) {
      lex->tkahead.token = losu_syntax_lex_next(
          lex, (losu_syntax_tkvalue_t)(&(lex->tkahead.info)));
      if (lex->tkahead.token == ':')
        __losu_syntaxpar_next(lex);

      losu_syntax_binder_concat(func, &el, losu_syntax_binder_jump(func));
      losu_syntax_binder_palist(func, v.value._bool.f,
                                losu_syntax_binder_getL(func));
      __losu_syntaxpar_next(lex);
      __losu_syntaxpar_statblock(lex);
      losu_syntax_binder_palist(func, el, losu_syntax_binder_getL(func));
      __losu_syntaxpar_checkmatch(lex, TOKEN_IF, TOKEN_PASS, line);
      break;
    } else {
      losu_syntax_binder_concat(func, &el, v.value._bool.f);
      losu_syntax_binder_palist(func, el, losu_syntax_binder_getL(func));
      break;
    }
  }

#undef condition
#undef then
}

static void __losu_syntaxpar_statwhile(losu_syntax_lex_t lex, int32_t line) {}

static void __losu_syntaxpar_statuntil(losu_syntax_lex_t lex, int32_t line) {}

static void __losu_syntaxpar_statfor(losu_syntax_lex_t lex, int32_t line) {}

static void __losu_syntaxpar_statfunc(losu_syntax_lex_t lex, int32_t line) {}

static void __losu_syntaxpar_statvar(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statname(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statreturn(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statbreak(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statcontinue(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statyield(losu_syntax_lex_t lex) {}

static void __losu_syntaxpar_statblock(losu_syntax_lex_t lex) {}

#endif

#if 1
#endif

#endif